package com.cv.platform.service.history;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.cv.framework.common.pojo.PageResult;
import com.cv.framework.common.utils.object.BeanUtils;
import com.cv.framework.mybatis.core.query.QueryWrapperX;
import com.cv.framework.security.core.utils.SecurityFrameworkUtil;
import com.cv.infra.api.file.FileApi;
import com.cv.platform.controller.platform.history.vo.CvVideoDetailHistoryRespVO;
import com.cv.platform.controller.platform.history.vo.CvVideoHistoryRespVO;
import com.cv.platform.controller.platform.history.vo.CvVideoHistorySaveReqVO;
import com.cv.platform.controller.platform.history.vo.CvVideoHistoryReqVO;
import com.cv.platform.controller.platform.label.vo.record.CvVideoLabelRespVO;
import com.cv.platform.dal.dataobject.history.CvVideoHistoryRecordDO;
import com.cv.platform.dal.dataobject.video.CvVideoDO;
import com.cv.platform.dal.es.index.video.CvVideoEntity;
import com.cv.platform.dal.mapper.history.CvVideoHistoryRecordMapper;
import com.cv.platform.service.label.CvVideoLabelService;
import com.cv.platform.service.video.CvVideoService;
import com.cv.system.api.user.UserApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 视频播放历史记录业务层接口实现类
 *
 * @author Charles_XDXD
 */
@Service
public class CvVideoHistoryRecordServiceImpl implements CvVideoHistoryRecordService {

    @Resource
    private CvVideoHistoryRecordMapper cvVideoHistoryRecordMapper;

    @Resource
    private CvVideoService cvVideoService;

    @Resource
    private CvVideoLabelService cvVideoLabelService;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private FileApi fileApi;

    @Override
    public List<CvVideoEntity> getAllVideoHistoryRecordByUserId(Long userId) {
        if (ObjUtil.isEmpty(userId)) {
            return Collections.emptyList();
        }

        QueryWrapperX<CvVideoHistoryRecordDO> wrapper = new QueryWrapperX<CvVideoHistoryRecordDO>()
                .eq("user_id", userId);

        List<CvVideoHistoryRecordDO> cvVideoHistoryRecordDOList = cvVideoHistoryRecordMapper.selectList(wrapper);

        if (CollUtil.isEmpty(cvVideoHistoryRecordDOList)) {
            return Collections.emptyList();
        }

        List<CvVideoEntity> cvVideoEntityList = new ArrayList<>();
        for (CvVideoHistoryRecordDO recordDO : cvVideoHistoryRecordDOList) {
            CvVideoDO videoDO = cvVideoService.getVideoById(recordDO.getVideoId());

            if (ObjUtil.isEmpty(videoDO)) {
                continue;
            }

            cvVideoEntityList.add(CvVideoEntity.builder()
                    .id(videoDO.getId())
                    .userId(videoDO.getUserId())
                    .nickname(userApi.getNicknameById(videoDO.getUserId()))
                    .title(videoDO.getTitle())
                    .type(videoDO.getType())
                    .labels(cvVideoLabelService.getAllLabelByVideoId(videoDO.getId())
                            .stream().map(CvVideoLabelRespVO::getLabelName)
                            .collect(Collectors.toList()))
                    .viewCount(videoDO.getViewCount())
                    .thumbnail(videoDO.getThumbnail())
                    .publishTime(videoDO.getCreateTime())
                    .build());
        }
        return cvVideoEntityList;
    }

    @Override
    public CvVideoDetailHistoryRespVO getVideoHistoryRecord(Long videoId) {
        if (ObjUtil.isNotEmpty(videoId)) {
            QueryWrapperX<CvVideoHistoryRecordDO> wrapper = new QueryWrapperX<CvVideoHistoryRecordDO>()
                    .eq("user_id", SecurityFrameworkUtil.getLoginUserId())
                    .eq("video_id", videoId);

            CvVideoHistoryRecordDO recordDO = cvVideoHistoryRecordMapper.selectOne(wrapper);
            if (ObjUtil.isEmpty(recordDO)) {
                return null;
            }
            return BeanUtils.toBean(recordDO, CvVideoDetailHistoryRespVO.class);
        }
        return null;
    }

    @Override
    public void saveVideoHistoryRecord(CvVideoHistorySaveReqVO reqVO) {
        if (ObjUtil.isNotEmpty(reqVO)) {
            // 存在历史记录，新增视频播放量
            cvVideoService.addVideoViewCount(reqVO.getVideoId());
            CvVideoHistoryRecordDO recordDO = BeanUtils.toBean(reqVO, CvVideoHistoryRecordDO.class);
            recordDO.setUserId(SecurityFrameworkUtil.getLoginUserId());

            CvVideoDetailHistoryRespVO record = getVideoHistoryRecord(reqVO.getVideoId());
            if (ObjUtil.isNotEmpty(record)) {
                recordDO.setId(record.getId());
            }
            cvVideoHistoryRecordMapper.insertOrUpdate(recordDO);
        }
    }

    @Override
    public void deleteVideoHistoryRecord(Long videoId) {
        Long userId = SecurityFrameworkUtil.getLoginUserId();
        if (ObjUtil.isNotEmpty(videoId) && ObjUtil.isNotEmpty(userId)) {
            QueryWrapperX<CvVideoHistoryRecordDO> wrapper = new QueryWrapperX<CvVideoHistoryRecordDO>()
                    .eq("video_id", videoId)
                    .eq("user_id", userId);
            cvVideoHistoryRecordMapper.delete(wrapper);
        }
    }

    @Override
    public void clearVideoHistoryRecord() {
        Long userId = SecurityFrameworkUtil.getLoginUserId();
        if (ObjUtil.isNotEmpty(userId)) {
            QueryWrapperX<CvVideoHistoryRecordDO> wrapper = new QueryWrapperX<CvVideoHistoryRecordDO>()
                    .eq("user_id", userId);
            cvVideoHistoryRecordMapper.delete(wrapper);
        }
    }

    @Override
    public PageResult<CvVideoHistoryRespVO> getVideoHistoryRecordPage(CvVideoHistoryReqVO reqVO) {
        PageResult<CvVideoHistoryRespVO> pageResult = cvVideoHistoryRecordMapper.selectPage(reqVO);

        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty();
        }

        pageResult.getList().forEach(item -> {
            item.setNickname(userApi.getNicknameById(item.getUserId()));
            item.setAvatarUrl(fileApi.getUrl(userApi.getAvatarById(item.getUserId())));
            item.setThumbnailUrl(fileApi.getUrl(item.getThumbnail()));
        });

        return pageResult;
    }

}
